package main

import (
	"fmt"
	"net/http"

	"github.com/devfeel/middleware/cors"

	"github.com/devfeel/dotweb"
)

type User struct {
	Name string `form:"name"`
	Age  int    `form:"age"`
}

func main() {
	//r:= http.Response
	//r1:= http.ResponseWriter
	app := dotweb.New()
	app.HttpServer.POST("/user", func(ctx dotweb.Context) error {
		user := new(User)
		if err := ctx.BindJsonBody(user); err != nil {
			return ctx.WriteString("Bind err:" + err.Error())
		}

		return ctx.WriteStringC(http.StatusOK, "Bind:"+fmt.Sprint(user))
	})
	userCenterGroup := app.HttpServer.Group("/usercenter")
	
	userCenterGroup.GET("/userinfo", func(ctx dotweb.Context) error {
		return nil
	})
	userCenterGroup.GET("/account", func(ctx dotweb.Context) error {
		return nil
	})

	app.HttpServer.GET("/hello", func(ctx dotweb.Context) error {
		return ctx.WriteString("hello " + ctx.QueryString("name"))
	})
	app.HttpServer.GET("/hello/:name", func(ctx dotweb.Context) error {
		fmt.Println(ctx.QueryString("name"))

		return ctx.WriteString("hello " + ctx.GetRouterName("name"))
	})
	app.HttpServer.GET("/news/:category/:newsid", func(ctx dotweb.Context) error {
		category := ctx.GetRouterName("category")
		newsid := ctx.GetRouterName("newsid")
		return ctx.WriteString("news info: category=" + category + " newsid=" + newsid)
	})
	app.HttpServer.POST("/upload", func(ctx dotweb.Context) error {
		ctx.File("upload")
		return nil
	})

	app.HttpServer.Renderer().SetTemplatePath("views/")
	app.HttpServer.GET("/", func(ctx dotweb.Context) error {
		ctx.ViewData().Set("data", "图书信息")
		type BookInfo struct {
			Name string
			Size int64
		}
		m := make([]*BookInfo, 5)
		m[0] = &BookInfo{Name: "book0", Size: 1}
		m[1] = &BookInfo{Name: "book1", Size: 10}
		m[2] = &BookInfo{Name: "book2", Size: 100}
		m[3] = &BookInfo{Name: "book3", Size: 1000}
		m[4] = &BookInfo{Name: "book4", Size: 10000}
		ctx.ViewData().Set("Books", m)

		err := ctx.View("test/testview.html")

		return err
	})
	app.HttpServer.GET("/redirect", func(ctx dotweb.Context) error {
		//内部重定向
		ctx.Redirect(http.StatusMovedPermanently, "src/1.html")
		//外部的重定向
		ctx.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
		return nil
	})
	
	app.Use(cors.DefaultMiddleware())
	app.HttpServer.ServerFile("/src/*filepath", "var/www")
	//app.HttpServer()..ServerFile("/*filepath", "/devfeel/dotweb/public")

	app.StartServer(8888)
}
